// manager/pages/creditrecord/index.js
import config from '../../../utils/config';
import { getSystemInfo } from '../../../utils/getSystemInfo';
import { request } from '../../../utils/request';
import util from '../../../common/util';
import WxValidate from '../../../common/WxValidate';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: config.baseUrl,
        userInfo: {},
        activeIndex: 0,
        tabList: [],
        showFilter: false,
        params: {
            custType: "",
            search: "",
            phone: "",
            sts: 1,
        },
        creditStsList: [],
        creditStsIndex: 0,
        scroller: {
			pageNum: 0,
			pageSize: 10,
			totalPage: 10,
			isNoneLoading: true,
			refreshColor: '#000000',
			refreshDiy: false,
			isloaded: false,
			list: []
        },
        show: false,
        actions: [],
        callItem: {},
        // 转交
        depList: [],
        custList: [],
        showTransfer: false,
        transferForm: {
            name: "",
            priorCreditId: "",
            recipientDeptId: "",
            recipientId: ""
        },
        // 统计
        perCreditLimit: null,
        perCreditNum: null,
        allBanksCreditLimit: null,
        allBanksCreditLimitLineOption: null,
        allBanksCreditNum: null,
        allBanksCreditNumBarOption: null,

        organCreditLimitRank: [],
        perCreditLimitRank: [],
        merCreditLimitRank: [],
        markeCreditLimitRank: [],
        perMarkeCreditLimitRank: [],
        merMarkeCreditLimitRank: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            activeIndex: Number(options.index) || 0
        })
        this.initValidate();
        this.getUserInfo();
        this.getSameLevelDepts();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getDictionaryInfo();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    // 获取当前登录者的用户信息
    getUserInfo(e) {        
        request({
            url: "/user/getUserInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {}
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    userInfo: res.data.userInfo
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 获取客户类型字典
     */
    getDictionaryInfo() {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
				dictType: "ecard_cust_type"
			}
        }).then(res => {
            if(res.code == 0){
                console.log(res)
                this.setData({
                    'params.custType': res.data.length > 0 ? res.data[this.data.activeIndex].dictValue : "",
                    tabList: res.data.concat([{
                        dictValue: "tj01",
                        dictLabel: "统计"
                    }])
                })
            }

            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "ecard_pre_credit_sts"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    creditStsList: res.data
                })

                this.resetParams();
                this.resetScroller();
                this.getData();
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    resetScroller(){
        let scroller = {
			pageNum: 0,
			pageSize: 10,
			totalPage: 10,
			isNoneLoading: true,
			refreshColor: '#000000',
			refreshDiy: false,
			isloaded: false,
			list: []
		}
		this.setData({
			scroller,
		})
    },
    /**
     * 验证params是否有值
     */
    validateParams(){
        let isFilter = false;
        let { params } = this.data;
        for(let key in params){
            if(['custType', 'sts'].indexOf(key) == -1 && params[key]){
                isFilter = true;
            }
        }
        this.setData({
            isFilter
		})
    },
    /**
     * 重置参数
     */
    resetParams(){
        let { params } = this.data;
        Object.keys(params).forEach(key => {
            if(key != "custType"){
                if(key == 'sts'){
                    params[key] = '1'
                }else{
                    params[key] = ''
                }
            }
        })
		this.setData({
            params,
            creditStsIndex: 0,
            isFilter: false
		})
    },
    /** 分类点击事件*/
    tabChange(e) {
        let { index } = e.currentTarget.dataset;
        this.resetParams();
        this.resetScroller();
        this.setData({
            'params.custType': this.data.tabList[index].dictValue,
            activeIndex: index,
        });
        this.getData();
    },

    /**
     * 获取数据
     */
    getData() {
        let { activeIndex } = this.data;
        switch(activeIndex){
            case 0:
                this.getPriorCreditList()
                break;
            case 1: 
                this.getPriorCreditList()
                break;
            case this.data.tabList.length - 1: 
                this.getPriorCreditLimit()
                this.getPriorCreditNum()
                this.getAllPriorCreditLimit()
                this.getLimitLineChart()
                this.getAllPriorCreditNum()
                this.getNumLineChart()
                this.getDeptPriorCreditList(0,'organCreditLimitRank')
                this.getDeptPriorCreditList(1,'perCreditLimitRank')
                this.getDeptPriorCreditList(2,'merCreditLimitRank')
                this.getUserPriorCreditList(0,'markeCreditLimitRank')
                this.getUserPriorCreditList(1,'perMarkeCreditLimitRank')
                this.getUserPriorCreditList(2,'merMarkeCreditLimitRank')
                break;
            default: 
                break;
        }
    },

    /**
     * 显示筛选
     */
    showFilterPopup(){
        this.setData({
            showFilter: true
        })
    },
    /**
     * 关闭筛选
     */
    closeFilter(){
        this.setData({
            showFilter: false
        })
    },
    /**
     * 确认筛选
     */
    confirmFilter(){
        this.setData({
            showFilter: false
        })
        this.validateParams();
        this.resetScroller();
        this.getData();
    },
    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['params.'+key]: e.detail.value,
        })
    },
    // 搜索
    searchConfirm(e){
        console.log(e)
        let key = e.currentTarget.dataset.key;
        this.setData({
            ['params.'+key]: e.detail.value,
            showFilter: false
        })
        // 页面加载时执行一次加载
        this.validateParams();
		this.resetScroller()
        this.getData();
    },
    // 预授信状态
    bindPickerChange(e){
        this.setData({
            creditStsIndex: e.detail.value,
            'params.sts': this.data.creditStsList[e.detail.value].dictValue
        })
    },
    /**
     * 获取预授信列表
     */
    getPriorCreditList() {
		let { scroller, params } = this.data;
        scroller.pageNum = scroller.pageNum + 1;
        if(scroller.pageNum>scroller.totalPage){
            return
        }
        request({
            url: `/priorCredit/getPriorCreditList`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                ...params,
                type: 1,
                pageNum: this.data.scroller.pageNum,
                pageSize: this.data.scroller.pageSize,
            }
        }).then(res => {
            if(res.code == 0){
                console.log(res)
                scroller.totalPage = Math.ceil(res.total/scroller.pageSize);
                if(scroller.pageNum>=scroller.totalPage){
                    scroller.isNoneLoading = false;
                }
                if(res.data.length>0){
                    res.data.map(item => {
                        item.beginDay = util.formatDate(new Date(item.beginDay));
                        item.endDate = util.formatDate(new Date(item.endDate));
                        return item
                    })
                }
                if(scroller.pageNum == 1){
                    scroller.list = res.data;
                }else{
                    scroller.list = scroller.list.concat(res.data);
                }
                this.setData({
                    scroller
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    
	refresh: function () {
        this.resetScroller()
		this.getData();
    },
    
	loadMore: function () {
        console.log("loadMore")
		this.getData();
    },

    /**
     * 跳转个人预授信详情
     */
    toPersonalcreditdesc(e) {
        let { id } = e.currentTarget.dataset;
        wx.navigateTo({
          url: `/manager/pages/personalcreditdesc/index?id=${id}`,
        })
    },

    /**
     * 跳转商户预授信详情
     */
    toMerchantcreditdesc(e) {
        let { id } = e.currentTarget.dataset;
        wx.navigateTo({
          url: `/manager/pages/merchantcreditdesc/index?id=${id}`,
        })
    },
    /**
     * 拨打电话
     */
    makePhoneCall(e) {
        console.log(e)
        let { item } = e.currentTarget.dataset;
        if(!item.phone){
            wx.showToast({
                title: "暂无联系方式",
                icon: 'none',
                duration: 2000
            })
            return
        }
        getSystemInfo({
            android: () => {
                let actions = [
                    { name: item.phone, color: '#999', disabled: true },
                    { name: '呼叫', color: '#000' },
                ]
                this.setData({
                    show: true,
                    callItem: item,
                    actions
                })
            },
            ios: () => {
                wx.makePhoneCall({
                    phoneNumber: item.phone
                })
            }
        })
    },
    onSelect(e) {
        console.log(e)
        this.setData({
            show: false
        })
        wx.makePhoneCall({
            phoneNumber: this.data.callItem.contactsPhone
        })
    },
    onCancel() {
        this.setData({ show: false });
    },

    /**
     * 获取同级部门列表
     */
    getSameLevelDepts() {
        request({
            url: `/dept/getSameLevelDepts`,
            method: "GET"
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    depList: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 根据机构ID获取客户经理
     */
    getUserListByDeptId(deptId) {
        request({
            url: `/user/getUserListByDeptId`,
            method: "GET",
            reqRSAENCRY: false, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                deptId
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    custList: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 选择框变化时
     */
    pickerChagne(e){
        let { key, value } = e.detail;
        if(key == "recipientDeptId"){
            if(value == this.data.transferForm.recipientDeptId){
               return 
            }
            this.getUserListByDeptId(value)
            this.setData({
                ['transferForm.'+key]: value,
                "transferForm.recipientId": ""
            })
        }else{
            this.setData({
                ['transferForm.'+key]: value
            })
        }
        
    },
    /** 转交弹窗 */
    transferMerchant(e){
        let { item } = e.currentTarget.dataset;
        let { transferForm } = this.data;
        transferForm.name = item.name;
        transferForm.priorCreditId = item.id;
        this.setData({
            showTransfer: true,
            transferForm
        })
    },
    /** 取消转交 */
	closeTransfer(e){
		this.setData({
			showTransfer: false
		})
	},
	/** 确认转交 */
	confirmTransfer(e){

        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.transferForm)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }

        request({
            url: `/priorCredit/addTransferPriorCredit`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: this.data.transferForm
        }).then(res => {
            if(res.code == 0){
                if(res.code == 0){
                    wx.showToast({
                        title: '转交成功',
                        icon: 'none',
                        mask: true,
                        duration: 2000
                    });
                    this.setData({
                        showTransfer: false
                    })
                    this.getData();
                }
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    // 表单验证
    initValidate() {
        // 验证字段的规则
        const rules = {
            recipientDeptId: {
                required: true
            },
            recipientId: {
                required: true
            }
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            recipientDeptId: {
                required: '请选择转交机构',
            },
            recipientId: {
                required: '请选择转交客户经理'
            }
        }

        // 创建实例对象
        this.WxValidate = new WxValidate(rules, messages)
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },

    /** 删除 */
    deleteMerchant(e){
        let { item } = e.currentTarget.dataset;
        console.log(item)
        let that = this;
        wx.showModal({
            title: '提示',
            content: `是否作废该预授信信息？`,
            success (res) {
                if (res.confirm) {
                    request({
                        url: `/priorCredit/delectPriorCredit`,
                        // method: "GET",
                        reqRSAENCRY: true, // 参数是否加密
                        resRSADECRY: false, // 返回值是否解密
                        data: {
                            id: item.id
                        }
                    }).then(res => {
                        if(res.code == 0){
                            if(res.code == 0){
                                wx.showToast({
                                    title: '作废成功',
                                    icon: 'none',
                                    mask: true,
                                    duration: 2000
                                });
                                setTimeout(()=>{
                                    that.resetScroller()
                                    this.getData();
                                },2000)
                            }
                        }
                    }).catch(error => {
                        // console.log(error)
                    })
                    // console.log('用户点击确定')
                } else if (res.cancel) {
                    // console.log('用户点击取消')
                }
            }
        })
    },
    /** 个人统计概况-额度 */
    getPriorCreditLimit(){
        request({
            url: `/priorCredit/getPriorCreditLimit`,
            // method: "GET",
            reqRSAENCRY: false, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    perCreditLimit: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /** 个人统计概况-户数 */
    getPriorCreditNum(){
        request({
            url: `/priorCredit/getPriorCreditNum`,
            // method: "GET",
            reqRSAENCRY: false, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    perCreditNum: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /** 全行统计概况-额度 */
    getAllPriorCreditLimit(){
        request({
            url: `/priorCredit/getAllPriorCreditLimit`,
            // method: "GET",
            reqRSAENCRY: false, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    allBanksCreditLimit: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /** 全行统计概况-额度折线图 */
    getLimitLineChart(){
        request({
            url: `/priorCredit/getLimitLineChart`,
            // method: "GET",
            reqRSAENCRY: false, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
        }).then(res => {
            if(res.code == 0){
                let color = ['#6794de', '#62c7c9']
                var option = {
                    color: color,
                    legend: {
                        data: [],
                        bottom: 15,
                        left: 'center',
                        // z: 100
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: true,
                        axisLabel: {
                            rotate: 45
                        },
                        data: [],
                    },
                    series: [],
                };
                if(res.data.length>0){
                    let o = {};
                    res.data.forEach(item => {
                        if(o[item.custType]){
                            o[item.custType].month.push(item.month);
                            o[item.custType].data.push(item.priorCreditLimit);
                        }else{
                            o[item.custType] = {
                                key: item.custType,
                                month: [item.month],
                                data: [item.priorCreditLimit]
                            }
                        }
                    })
                    
                    let i = 0;
                    Object.keys(o).map((key)=>{
                        option.legend.data.push(o[key].key);
                        option.xAxis.data = o[key].month;            
                        option.series.push({
                            name: o[key].key,
                            type: 'line',
                            label: {
                                show: true,
                                position: 'top',
                                distance: 0,
                                formatter: '{c}',
                                textStyle: {
                                    color: color[i%2],
                                    fontSize: 12
                                }
                            },
                            // smooth: true,
                            data: o[key].data
                        });
                        i++
                    })
                }
                this.setData({
                    allBanksCreditLimitLineOption: option
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /** 全行统计概况-户数 */
    getAllPriorCreditNum(){
        request({
            url: `/priorCredit/getAllPriorCreditNum`,
            // method: "GET",
            reqRSAENCRY: false, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    allBanksCreditNum: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /** 全行统计概况-户数柱状图 */
    getNumLineChart(){
        request({
            url: `/priorCredit/getNumLineChart`,
            // method: "GET",
            reqRSAENCRY: false, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
        }).then(res => {
            console.log(res)
            if(res.code == 0){
                let color = ['#6794de', '#62c7c9']
                var option = {
                    color: color,
                    legend: {
                        data: [],
                        bottom: 15,
                        left: 'center',
                        // z: 100
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: true,
                        axisLabel: {
                            rotate: 45
                        },
                        data: [],
                    },
                    series: [],
                };
                if(res.data.length>0){
                    let o = {};
                    res.data.forEach(item => {
                        if(o[item.custType]){
                            o[item.custType].month.push(item.month);
                            o[item.custType].data.push(item.priorCreditNum);
                        }else{
                            o[item.custType] = {
                                key: item.custType,
                                month: [item.month],
                                data: [item.priorCreditNum]
                            }
                        }
                    })
                    let i = 0;
                    Object.keys(o).map((key)=>{
                        option.legend.data.push(o[key].key);
                        option.xAxis.data = o[key].month;            
                        option.series.push({
                            name: o[key].key,
                            type: 'bar',
                            barGap: '0%',
                            itemStyle: {
                                // borderWidth: 1,
                                borderRadius: [0, 0, 0, 0],
                                color: color[i%2],
        
                            },
                            // smooth: true,
                            data: o[key].data
                        });
                        i++
                    })
                }
                this.setData({
                    allBanksCreditNumBarOption: option
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    }, 
    /** 各机构预授信业务总排名 custType：客户类型，0全部，1个人，2商户 */
    getDeptPriorCreditList(custType,key){
        request({
            url: `/priorCredit/getDeptPriorCreditList`,
            // method: "GET",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                custType,
                pageNum: 1,
                pageSize: 5,
            }
        }).then(res => {
            console.log(res)
            if(res.code == 0){
                this.setData({
                    [key]: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },   
    /** 各机构查看更多 */
    toOrgrank(e){
        console.log(e.currentTarget.dataset)
        let { type } =  e.currentTarget.dataset;
        wx.navigateTo({
          url: `/manager/pages/gridmerchantorgrank/index?type=${type}`,
        })
    },
    /** 营销人员预授信业务总排名 custType：客户类型，0全部，1个人，2商户 */
    getUserPriorCreditList(custType,key){
        request({
            url: `/priorCredit/getUserPriorCreditList`,
            // method: "GET",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                custType,
                pageNum: 1,
                pageSize: 5,
            }
        }).then(res => {
            console.log(res)
            if(res.code == 0){
                this.setData({
                    [key]: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },   
    /** 营销人员查看更多 */
    toMarkerank(e){
        console.log(e.currentTarget.dataset)
        let { type } =  e.currentTarget.dataset;
        wx.navigateTo({
          url: `/manager/pages/gridmerchantmarkerank/index?type=${type}`,
        })
    },
})